package com.sx.zongzhi.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.sx.zongzhi.R;
import com.sx.zongzhi.activity.AboutActivity;
import com.sx.zongzhi.activity.CheckInActivity;
import com.sx.zongzhi.activity.LoginActivity;
import com.sx.zongzhi.activity.PasswordSetActivity;
import com.sx.zongzhi.activity.PersonInformationActivity;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.bean.VersionBean;
import com.sx.zongzhi.net.ServiceFactory;
import com.sx.zongzhi.presenter.VersionPest;
import com.sx.zongzhi.utils.BaseUtil;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.utils.UpdateVersionUtil;
import com.sx.zongzhi.view.IVersionView;
import com.sx.zongzhi.widget.CustomDialog;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * Created by XZY on 2017/11/21.
 * 我的
 */
public class MyFragment extends Fragment implements IVersionView{


    @BindView(R.id.imv_Head)
    ImageView imvHead;
    @BindView(R.id.tv_City)
    TextView tvCity;
    @BindView(R.id.tv_Name)
    TextView tvName;
    @BindView(R.id.tv_Phone)
    TextView tvPhone;
    @BindView(R.id.tl_bt)
    ToggleButton tl_bt;
    @BindView(R.id.tv_Version)
    TextView tv_Version;
    @BindView(R.id.tv_New)
    TextView tv_New;

    private IDataStorage dataStorage;
    private Disposable disposable;
    private VersionBean versionBean;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my, container, false);
        ButterKnife.bind(this, view);
        dataStorage = DataStorageFactory.getInstance(
                getActivity(), DataStorageFactory.TYPE_DATABASE);
        if (dataStorage.contains(UserBean.class,getActivity().getPackageName())){
            UserBean userBean = dataStorage.load(UserBean.class,getActivity().getPackageName());
            String orgName = userBean.getOrg() == null ? "": userBean.getOrg().getOrgName();
            tvCity.setText(orgName);
            tvName.setText(userBean.getName());
            tvPhone.setText(userBean.getMobile());
            RequestOptions options = new RequestOptions().centerCrop()
                    .placeholder(R.mipmap.head_default)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .circleCrop()
                    .error(R.mipmap.head_default);
            Glide.with(getActivity())
                    .load(ServiceFactory.NEW_API_BASE_URL+ File.separator + userBean.getHeaderUrl())
                    .apply(options)
                    .into(imvHead);
        }
        initRx();
        new VersionPest(this).getVersion();
        return view;
    }

    private void initRx() {
        tv_Version.setText("当前版本"+ BaseUtil.getAppVersionName(getActivity())+"");
        disposable =  MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent msgEvent) throws Exception {
                        if ("MyFragment".equals(msgEvent.getRequest())) {
                            if (msgEvent.getType()==1){
                                UserBean bean= (UserBean) msgEvent.getMsg();
                                String orgName = bean.getOrg() == null ? "" : bean.getOrg().getOrgName();
                                tvCity.setText(orgName);
                                tvName.setText(bean.getName());
                                tvPhone.setText(bean.getMobile());
                                RequestOptions options = new RequestOptions().centerCrop()
                                        .placeholder(R.mipmap.head_default)
                                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                                        .circleCrop()
                                        .error(R.mipmap.head_default);
                                Glide.with(getActivity())
                                        .load(ServiceFactory.NEW_API_BASE_URL + File.separator + bean.getHeaderUrl())
                                        .apply(options)
                                        .into(imvHead);
                            }

                        }
                    }
                });

        tl_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tl_bt.isChecked()){
                    JPushInterface.resumePush(getActivity().getApplicationContext());
                }else {
                    JPushInterface.stopPush(getActivity().getApplicationContext());
                }
                if (dataStorage.contains(UserBean.class,getActivity().getPackageName())){
                    UserBean userBean = dataStorage.load(UserBean.class,getActivity().getPackageName());
                    userBean.setJuPush(tl_bt.isChecked());
                    dataStorage.storeOrUpdate(userBean,getActivity().getPackageName());
                }
            }
        });
    }



    @OnClick({R.id.rl_Head, R.id.tv_PwdSet, R.id.tv_About, R.id.bt_ExitLogin,R.id.rl_Version,R.id.tv_checkin})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.rl_Head:
                startActivity(new Intent(getActivity(), PersonInformationActivity.class));
                break;
            case R.id.tv_PwdSet:
                startActivity(new Intent(getActivity(), PasswordSetActivity.class));
                break;
            case R.id.tv_About:
                startActivity(new Intent(getActivity(), AboutActivity.class));
                break;
            case R.id.bt_ExitLogin:
                createLogin();
                break;
            case R.id.rl_Version:
                if (versionBean!=null){
                    if (versionBean.getVersion()>BaseUtil.getVersionCode(getActivity())){
                        UpdateVersionUtil.showDialog(getActivity(),view,versionBean);
                    }else {
                        ToastUtils.showToast(getActivity(),"当前已是最新版");
                    }
                }else {
                    ToastUtils.showToast(getActivity(),"当前已是最新版");
                }
                break;
            case R.id.tv_checkin:
                startActivity(new Intent(getActivity(), CheckInActivity.class));
                break;
        }
    }

    private void createLogin() {
        CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        CustomDialog dialog = builder.setMessage("确定退出当前账号？").
                setBackButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setConfirmButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(getActivity(), LoginActivity.class));
                dialog.dismiss();
            }
        }).create();
        dialog.show();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
    @Override
    public void onDestroy() {
        if (disposable != null){
            disposable.dispose();
        }
        super.onDestroy();
    }

    @Override
    public void getVersion(VersionBean versionBean) {
        if (versionBean!=null){
            this.versionBean=versionBean;
            if (versionBean.getVersion()>BaseUtil.getVersionCode(getActivity())){
                tv_New.setVisibility(View.VISIBLE);
            }else {
                tv_New.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void showError(String message) {
        ToastUtils.showToast(getActivity(),message);
    }
}
